/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.silverfoxserver.ext.socket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 *
 * @author ACER-FX
 */
public class BinaryWebSocketFrameHandler extends
        SimpleChannelInboundHandler<BinaryWebSocketFrame> {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    
    /**
     * 在Netty 4.x里，原来3.x的 channelOpen, 
     * channelConnect事件被集成为一个，即channelActive
     * 
     * @param ctx
     * @throws Exception 
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        System.out.println("Client:"+incoming.remoteAddress()+"在线");
    }
    
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    
        int len = msg.content().readableBytes();
        
        ByteBuf cc = msg.content().copy();//duplicate();
        

        byte[] bb = new byte[len];
        
        int i =0;
        
        while(msg.content().isReadable())
        {
            bb[i] = msg.content().readByte();
            i++;
        }
        
        
        
        String bStr = new String(bb);
        
        
        //1、字节数组转换为字符串
        //byte[] byBuffer = new byte[20];
        //... ...
        //String strRead = new String(byBuffer);
        
        
         Channel incoming = ctx.channel();
        for (Channel channel : channels) {
        if (channel != incoming){
        //channel.writeAndFlush(new TextWebSocketFrame("[" + incoming.remoteAddress() + "]"));
        } else {
        //channel.writeAndFlush(new TextWebSocketFrame("[you]"));
        }
        
        channel.writeAndFlush(new BinaryWebSocketFrame(cc));
        
    }
    

    
        
       
        
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
        Channel incoming = ctx.channel();

        // Broadcast a message to multiple Channels
        channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + " 加入"));

        channels.add(incoming);
            System.out.println("Client:"+incoming.remoteAddress() +"加入");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
        Channel incoming = ctx.channel();

        // Broadcast a message to multiple Channels
        channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + " 离开"));

            System.out.println("Client:"+incoming.remoteAddress() +"离开");

        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
        }

    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        System.out.println("Client:"+incoming.remoteAddress()+"掉线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("Client:"+incoming.remoteAddress()+"异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }

    

}
